package hypeerweb;

import java.net.InetAddress;

import proxyCommand.*;

/**
 * HyPeerWeb is on the default port.
 * 
 * All GUIs are on port 49153
 *
 */

public class HyPeerWebClientServer {

	public static void main(String[] args) {
		try {

			if(args.length == 1) {
				
				System.out.println("Starting The first HyPeerWeb Segment");
				
				GlobalObjectId thisGlobalObjectId = new GlobalObjectId(InetAddress.getLocalHost().getHostAddress(),
						new PortNumber(Integer.parseInt(args[0])),
						new LocalObjectId());
				
				System.out.println(thisGlobalObjectId.getMachineAddr());
				System.out.println(thisGlobalObjectId.getPortNumber());
				System.out.println(thisGlobalObjectId.getLocalObjectId());
			
				HyPeerWeb.getSingleton(thisGlobalObjectId);
				//SET THE GLOBAL OBJECT ID!
			
				//store the hypeerweb into the objectDB 
				ObjectDB curDB = ObjectDB.getSingleton();
				curDB.store(thisGlobalObjectId.getLocalObjectId(), (Object)HyPeerWeb.getSingleton(thisGlobalObjectId));
			
				curDB.dump();
				PeerCommunicator.createPeerCommunicator(new PortNumber(Integer.parseInt(args[0])));

				System.out.println("Finished launching hypeerweb and adding it to the database");
			}
			else {
				
				System.out.println("Starting adding a HyPeerWeb Segment to the HyPeerWeb");
				GlobalObjectId nextGlobalObjectId = new GlobalObjectId(args[0],
														new PortNumber(Integer.parseInt(args[1])),
														new LocalObjectId(Integer.parseInt(args[2])));
				HyPeerWebProxy nextSegment = HyPeerWebProxy.getSingleton(nextGlobalObjectId);
				
				GlobalObjectId thisGlobalObjectId = new GlobalObjectId(InetAddress.getLocalHost().getHostAddress(),
														new PortNumber(Integer.parseInt(args[3])),
														new LocalObjectId());
				
				System.out.println(thisGlobalObjectId.getMachineAddr());
				System.out.println(thisGlobalObjectId.getPortNumber());
				System.out.println(thisGlobalObjectId.getLocalObjectId());
				
				ObjectDB curDB = ObjectDB.getSingleton();
				curDB.store(thisGlobalObjectId.getLocalObjectId(), (Object)HyPeerWeb.getSingleton(nextSegment, thisGlobalObjectId));
				
				curDB.dump();
				PeerCommunicator.createPeerCommunicator(thisGlobalObjectId.getPortNumber());
				
				nextSegment.addSegment(thisGlobalObjectId, nextGlobalObjectId);
			}
		}
		catch (Exception e) {
			e.printStackTrace();
		}

	}
}
